package com.liuwei.msmall.seckill.scheduled;

import com.liuwei.msmall.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Classname SeckillScheduled
 * @Date 2020/10/18 17:56
 * @Created by 刘
 */
@Component
@Slf4j
public class SeckillScheduled {

    @Autowired
    SeckillService seckillService;

    @Autowired
    RedissonClient redissonClient;
    //上架秒杀商品的分布式锁
    private final String upload_lock = "seckill:upload:lock";

    /**
     * 每天晚上凌晨3点定时异步任务，扫描近3天的秒杀活动
     * 每分中执行一次
     */
//    @Async
    @Scheduled(cron = "0 * * * * ?")
    public void uploadSkuLatest3Days(){

        //使用分布式锁来保证多个微服务执行的有序，防止出现竞争，同时执行
        RLock lock = redissonClient.getLock(upload_lock);
        //10s之后自动释放锁
        log.info("获取分布式锁。。。。");
        lock.lock(10, TimeUnit.SECONDS);
        try {
            //TODO 接口幂等性
            seckillService.uploadSkuLatest3Days();
            log.info("上架商品成功.....");
        }catch (Exception e){
            log.error("上架秒杀商品出现异常。。。",e.getMessage());
        } finally {
            //无论执行是否成功，都释放锁
            log.info("释放分布式锁。。");
            lock.unlock();
        }

    }

}
